#ifndef CONNECTOR_HEADER_
#define CONNECTOR_HEADER_

#include <winsock2.h>
#include "DebugUtil.h"
#include <assert.h>
#include "Handler.h"
struct NetAddr;

template<typename HandlerType>
class Connector
{
public:
	Connector()
	{
		handler = 0;
	}
public:
	bool connectServer(const NetAddr& _addr)
	{
		SOCKET sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
		if(INVALID_SOCKET == sock)
		{
			assert(!"got an error while creating socket\n");
			return false;
		}
		sockaddr_in srvAddr={0};
		srvAddr.sin_family = AF_INET;
		srvAddr.sin_addr.s_addr = inet_addr(_addr.addr);
		srvAddr.sin_port = htons(_addr.port);
		if(SOCKET_ERROR==connect(sock,(sockaddr*)(&srvAddr),sizeof(srvAddr)))
		{
			int err = WSAGetLastError();
			PR("connect to server error:[%d]\n",err);
			//assert(!"connect error");
			return false;
		}
		Handler* handler = new HandlerType;
		this->handler = handler;
		this->sock = sock;
		handler->setHandle(sock);
		handler->start();
		return true;
	}
	Handler* handler;
	SOCKET sock;
};

#endif